﻿using System.Xml;
using System.Xml.Linq;

namespace DIS.WindowsPhone.Toolkit
{
    /// <summary>
    /// Helper class for retrieving the information from the WMAppManifest.xml
    /// </summary>
    public class AppInfoHelper
    {
        private XDocument _appManifest;
        public XDocument AppManifestXML
        {
            get
            {
                return _appManifest;
            }
            set
            {
                _appManifest = value;
            }
        }

        /// <summary>
        /// Gets the Product ID specified in the ProductID attribute of the App element
        /// </summary>
        public string ProductId { get; private set; }

        /// <summary>
        /// Gets the Title specified in the Title attribute of the App element
        /// </summary>
        public string Title { get; private set; }

        /// <summary>
        /// Gets the Publisher specified in the Publisher attribute of the App element
        /// </summary>
        public string Publisher { get; private set; }

        /// <summary>
        /// Gets the Description specified in the Description attribute of the App element
        /// </summary>
        public string Description { get; private set; }

        /// <summary>
        /// Gets the Version specified in the Version attribute of the App element
        /// </summary>
        public string Version { get; private set; }

        /// <summary>
        /// Gets the Author specified in the Author attribute of the App element
        /// </summary>
        public string Author { get; private set; }

        public AppInfoHelper()
        {
            _appManifest = XDocument.Load("WMAppManifest.xml");
            this.ProductId = GetAppAttribute("ProductID");
            this.Title = GetAppAttribute("Title");
            this.Publisher = GetAppAttribute("Publisher");
            this.Description = GetAppAttribute("Description");
            this.Version = GetAppAttribute("Version");
            this.Author = GetAppAttribute("Author");
        }

        private string GetAppAttribute(string attributeName)
        {
            string appManifestName = "WMAppManifest.xml";
            string appNodeName = "App";

            if (AppManifestXML != null)
            {
                using (XmlReader rdr = AppManifestXML.CreateReader(ReaderOptions.None))
                {
                    rdr.ReadToDescendant(appNodeName);
                    if (!rdr.IsStartElement())
                        throw new System.FormatException(appManifestName + " is missing " + appNodeName);

                    return rdr.GetAttribute(attributeName);
                }
            }
            else
                return null;
        }
    }
}
